﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Wallpaper.Data.Context;
using Wallpaper.Models.Entities;

namespace Wallpaper.Data.Base
{
    public class BaseDal<T> : IBaseDal<T> where T : BaseEntity
    {
        protected readonly WallpaperDbContext _dbContext;
        protected readonly DbSet<T> _dbSet;

        public BaseDal(WallpaperDbContext dbContext)
        {
            _dbContext = dbContext;
            _dbSet = dbContext.Set<T>();
        }

        public async Task<bool> CreateEntityAsync(T entity)
        {
            await _dbSet.AddAsync(entity);
            return await _dbContext.SaveChangesAsync() > 0;
        }

        /// <summary>
        /// 先查本地缓存再查数据库-Find(主键查询​ ) 
        ///  ​条件查询 使用FirstOrDefaultAsync(u => u.Email == email);
        /// </summary>
        /// <param name="id">id</param>
        /// <returns></returns>
        public async Task<T> GetByIdAsync(string id)
        {
            return await _dbSet.FindAsync(id);
        }

        /// <summary>
        ///  查询立即执行（方法调用时即查询数据库）
        /// </summary>
        /// <returns></returns>
        public async Task<List<T>> GetAllAsync()
        {
            return await _dbSet.ToListAsync();
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="entity">实体类</param>
        /// <returns></returns>
        public async Task<bool> UpdateEntityAsync(T entity)
        {
            _dbSet.Update(entity);
            return await _dbContext.SaveChangesAsync() > 0;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="entity">实体类</param>
        /// <returns></returns>
        public async Task<bool> DeleteEntityAsync(T entity)
        {
            _dbSet.Remove(entity);
            return await _dbContext.SaveChangesAsync() > 0;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id">Id</param>
        /// <returns></returns>
        public async Task<bool> DeleteByIdAsync(string id)
        {
            var entity = await GetByIdAsync(id);
            if (entity != null)
            {
                return await DeleteEntityAsync(entity);
            }
            return false;
        }

        /// <summary>
        /// 查询延迟执行（后续操作时才真正查询数据库）
        /// </summary>
        /// <returns></returns>
        public IQueryable<T> GetQueryable()
        {
            return _dbSet.AsQueryable();
        }


    
        /// <summary>
        /// 查询
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public DbSet<T> GetDbSet<T>() where T : class
        {
            return _dbContext.Set<T>();
        }
    }
}
